package com.jp.knowledge.my.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.activity.ClipImageActivity;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.SelectDialog;
import com.jp.knowledge.http.HttpGet;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.logic.UploadLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.adapter.MyFileAboutAdapter;
import com.jp.knowledge.my.adapter.MyIndustryAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.business.MyFileBusiness;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ImageUtil;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.FlowLayout;
import com.jp.knowledge.view.JpRecycleView;
import com.jp.knowledge.wxapi.WXEntryActivity;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.jp.knowledge.view.ClipViewLayout.getRealFilePathFromUri;

/**
 * 档案
 *
 * @author gzejia 978862664@qq.com
 */
public class MyFileActivity extends SlidingActivity implements ResultSubscriber.OnResultListener, View.OnClickListener, HttpGet.HttpGetCallback {

    public static final String WEICHAT_LOGIN_STATE = "weiChatLoginState";

    //请求相机
    private static final int REQUEST_CAPTURE = 0x0000001;
    //请求相册
    private static final int REQUEST_PICK = 0x0000002;
    //请求截图
    private static final int REQUEST_CROP_PHOTO = 0x0000003;
    //修改用户信息
    private static final int UPDATE_USER_INFO = 0x0000004;

    //微信绑定获取 access_token
    private static final int WEICHAT_ACCESS_TOKEN_CODE = 0x0000005;
    //微信绑定获取个人信息
    private static final int WEICHAT_GET_USER_DATA = 0x0000006;
    // 提交微信绑定信息
    private static final int WEICHAT_DATA_COMMIT_CODE = 0x0000007;

    private WeiChatBindModel weiChatBindModel;

    private  int type =1;

    /**我的技能*/
    @ViewInject(R.id.my_kill)
    private TextView  myKill;

    @ViewInject(R.id.file_iv_header)
    private ImageView mHeaderIv;

    @ViewInject(R.id.file_tv_pet_name)
    private TextView mPetNameTv;

    @ViewInject(R.id.file_tv_user_name)
    private TextView mUserNameTv;

    @ViewInject(R.id.file_tv_sex)
    private TextView mSexTv;

    @ViewInject(R.id.file_tv_class)
    private TextView mClassTv;

    @ViewInject(R.id.file_tv_position)
    private TextView mPositionTv;

    @ViewInject(R.id.file_tv_phone)
    private TextView mPhoneTv;

    @ViewInject(R.id.file_tv_introduce)
    private TextView mIntroduceTv;

    @ViewInject(R.id.file_rv_about_role)
    private JpRecycleView mAboutRoleRv;

    @ViewInject(R.id.file_rv_about_trade)
    private JpRecycleView mAboutTradeRv;

    @ViewInject(R.id.file_tv_introduce)
    private TextView instro;

    @ViewInject(R.id.flow_layout)
    private FlowLayout flowLayout;


    @ViewInject(R.id.bind_weichat_lly)
    private LinearLayout bindWeiChatLly;
    @ViewInject(R.id.bind_weichat_tv)
    private TextView bindWeiChatTv;

    private File  tempFile;

    private PopupWindow popupWindow;
    private SelectDialog sexSelectDialog;
    private CommDialog saveDialog;

    private MyFileBusiness mBusiness = new MyFileBusiness();

    private String tempImgPath;
    private UserData userData;
    private PersonLogic personLogic;

    private List<UserData.SkillsBean>  roles;
    private List<UserData.IndustryBean> industrys;

    private MyFileAboutAdapter roleAdapter;
    private MyIndustryAdapter indusAdapter;

    private List<UserData.SkillsBean> addSkill;//添加技能列表
    private List<UserData.SkillsBean> delSkill;//删除技能列表

    private List<UserData.IndustryBean> addIndustry;//添加行业
    private List<UserData.IndustryBean> delIndustry;//删除行业

    private  List<UserData.SkillsBean>  tempSkills;
    private  List<UserData.IndustryBean> tempIndustrys;

    /* 接收微信绑定广播 */
    private BroadcastReceiver broadcaseReciver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction() != WXEntryActivity.WECHAT_BIND)
                return;
            int errCode = intent.getIntExtra(WXEntryActivity.WECHAT_BIND_ERR_CODE, -1);
            switch (errCode){
                case BaseResp.ErrCode.ERR_OK:
                    loading.show();
                    String code = intent.getStringExtra(WXEntryActivity.WECHAT_BIND_RESULT_CODE);
                    if(code == null) {
                        ToasUtil.toast(MyFileActivity.this, "抱歉，认证出错，请稍后重试");
                        return;
                    }
                    String appId = "wx73bea73b9ead58e8";
                    String secret = "9db2a5dda3f0ca977859cc9ad414a0b8";
                    String grant_type = "authorization_code";
                    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                            + "appId=" + appId
                            + "&secret=" + secret
                            + "&code=" + code
                            + "&grant_type=" + grant_type;
                    HttpGet.httpGetData(WEICHAT_ACCESS_TOKEN_CODE, url, MyFileActivity.this);
                    return;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    ToasUtil.toast(MyFileActivity.this, "微信授权被取消");
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    ToasUtil.toast(MyFileActivity.this, "获取微信授权失败");
                    break;
                default:
                    ToasUtil.toast(MyFileActivity.this, "未知错误");
            }
            loading.cancel();
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        loading.cancel();
    }

    private IWXAPI api;
    private void regToWx(){
        api = WXAPIFactory.createWXAPI(this, "wx73bea73b9ead58e8", true);
        api.registerApp("wx73bea73b9ead58e8");
    }

    @Override
    protected int getResourceId() {
        return R.layout.activity_my_file;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        createCameraTempFile(savedInstanceState);
    }

    @Override
    protected void init() {
        contentView.setBackgroundResource(R.color.gray_bg);
        roles = new ArrayList<>();
        industrys = new ArrayList<>();

        regToWx();

        userData =application.getUserData();//获取用户信息
        if(userData!=null) {
            tempSkills = userData.getSkills();
            tempIndustrys = userData.getIndustry();
        }
        tempImgPath =  mContext.getCacheDir()+"/imgs/";
        personLogic = new PersonLogic(mContext, new PersonLogic.UserDataCallBack() {
            @Override
            public void done(UserData data) {
                userData = data;
//                initOthers();
            }
        });

        initTitle();
        initOthers();
        initAboutRoleRv();
        initAboutTradeRv();
        initClickListenter();

        if(userData != null
                && userData.getOpenid() != null
                && userData.getOpenid().trim().length() > 0){
            bindWeiChatLly.setVisibility(View.GONE);        // 已经绑定了微信
        }

        sexSelectDialog = new SelectDialog(this);
        sexSelectDialog.setTitle("选择性别");
        sexSelectDialog.addItem("男");
        sexSelectDialog.addItem("女");
        sexSelectDialog.setOnDialogItemClickListener(new SelectDialog.OnSelectDialogItemClickListener() {
            @Override
            public void onSelectItemClick(int position) {
                if(position == 0){
                    mSexTv.setText("男");
                    setUserData(R.id.file_tv_sex, "男");
                } else if(position == 1){
                    mSexTv.setText("女");
                    setUserData(R.id.file_tv_sex, "女");
                }
            }
        });

        saveDialog = new CommDialog(this);
        saveDialog.setContent("是否保存信息？");
        saveDialog.setLeft("离开");
        saveDialog.setRight("保存");
        saveDialog.setRightListener(this);
        saveDialog.setLeftListener(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WXEntryActivity.WECHAT_BIND);
        registerReceiver(broadcaseReciver, intentFilter);
    }

    private void initClickListenter(){
        findViewById(R.id.file_lly_header).setOnClickListener(this);
        findViewById(R.id.file_lly_pet_name).setOnClickListener(this);
        findViewById(R.id.file_lly_user_name).setOnClickListener(this);
        findViewById(R.id.file_lly_sex).setOnClickListener(this);
        findViewById(R.id.file_lly_class).setOnClickListener(this);
        findViewById(R.id.file_lly_position).setOnClickListener(this);
        findViewById(R.id.file_lly_phone).setOnClickListener(this);
        findViewById(R.id.file_lly_introduce).setOnClickListener(this);
        findViewById(R.id.my_kill).setOnClickListener(this);
        findViewById(R.id.right_bn).setOnClickListener(this);
        findViewById(R.id.icon_left).setOnClickListener(this);
        findViewById(R.id.file_add_industry).setOnClickListener(this);
        bindWeiChatTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.file_lly_header:// 头像
                uploadHeadImage();
                break;
            case R.id.file_lly_pet_name:// 昵称
                goEditActivity(mPetNameTv.getText().toString(),"修改昵称",mPetNameTv.getId());
                break;
            case R.id.file_lly_user_name:// 姓名
                goEditActivity(mUserNameTv.getText().toString(),"修改姓名",mUserNameTv.getId());
                break;
            case R.id.file_lly_sex:// 性别
                sexSelectDialog.show();
                break;
            case R.id.file_lly_class:// 部门
                goEditActivity(mClassTv.getText().toString(),"修改部门",mClassTv.getId());
                break;
            case R.id.file_lly_position:// 职位
                goEditActivity(mPositionTv.getText().toString(),"修改职业",mPositionTv.getId());
                break;
            case R.id.file_lly_phone:// 手机
                goEditActivity(mPhoneTv.getText().toString(),"修改手机",mPhoneTv.getId());
                break;
            case R.id.file_lly_introduce:// 介绍
                goEditActivity(instro.getText().toString(),"一句话介绍",instro.getId());
                break;
            case R.id.icon_left:// 返回
//                finish();
                saveDialog.show();
                break;
            case R.id.my_kill:// 技能标签
                Intent intent = new Intent(mContext,MoreRoleActivity.class);
                intent.putExtra("skill",true);
                intent.putExtra("skilles", (Serializable) tempSkills);
                startActivityForResult(intent,MoreRoleActivity.ROLE_RESULT_CODE);
                break;
            case R.id.file_add_industry:// 技能标签
                Intent intentIndustry = new Intent(mContext,MoreRoleActivity.class);
                intentIndustry.putExtra("skill",false);
                intentIndustry.putExtra("industry", (Serializable) tempIndustrys);
                startActivityForResult(intentIndustry,MoreRoleActivity.INDUSTRY_RESULT_CODE);
                break;
            case R.id.left_btn:
                saveDialog.cancel();
                finish();
                break;
            case R.id.right_btn:
                saveDialog.cancel();
            case R.id.right_bn:// 保存按钮
                saveUserData();
                break;
            case R.id.bind_weichat_tv:// 绑定微信
                if (!api.isWXAppInstalled()){
                    ToasUtil.toast(this, "抱歉，你还未安装微信，请先安装后重试");
                } else {
                    loading.show();
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = WEICHAT_LOGIN_STATE;
                    api.sendReq(req);
                }
                break;
        }
    }

    /**
     * 去到修改页面
     * @param text
     * @param title
     */
    private void goEditActivity(String text,String title, int id){
        Intent intent = new Intent(mContext,EditUserDataActivity.class);
        intent.putExtra(EditUserDataActivity.EDITEXT_FLAG,text);
        intent.putExtra(EditUserDataActivity.EDITTITLE_FLAG,title);
        intent.putExtra("id",id);
        startActivityForResult(intent,EditUserDataActivity.RESULT_CODE);
    }

    private void initTitle() {
        topName.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
        topName.setText(R.string.my_tv_file);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        topDesc.setVisibility(View.GONE);
        rightIcon.setVisibility(View.GONE);
        rightBtn.setVisibility(View.VISIBLE);
            rightBtn.setText("保存");
    }


    /**
     * 初始化信息
     */
    private void initOthers() {

        // 为加入组织时不要显示部门和职位
        if(userData.getCompanyId() == null || userData.getCompanyId().length() == 0){
            findViewById(R.id.file_lly_class).setVisibility(View.GONE);
            findViewById(R.id.file_lly_position).setVisibility(View.GONE);
        }

        try {
            mHeaderIv.setImageResource(R.mipmap.ic_my_header);
            mPetNameTv.setText(userData.getNickname());
            mUserNameTv.setText(userData.getUsername());
            mSexTv.setText(userData.getGender());
            mPhoneTv.setText(userData.getPhone());

            mClassTv.setText(userData.getDepartment());
            mPositionTv.setText(userData.getPosition());
            mIntroduceTv.setText(userData.getUserIntro());

            ImageLoadUtil.loadCircle(mContext,userData.getPortrait(),mHeaderIv);
        }catch (Exception e){

        }
    }

    private void initAboutRoleRv() {
        if(userData!=null) {
           tempSkills= userData.getSkills();
           roles=userData.getSkills();
            mAboutRoleRv.setHasFixedSize(true);
            mAboutRoleRv.setLayoutManager(new GridLayoutManager(this, 3));
            roleAdapter= new MyFileAboutAdapter(this,tempSkills);
            roleAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
                @Override
                public void itemSelect(int position) {
                }
            });
            mAboutRoleRv.setAdapter(roleAdapter);

            initFlowLayout(tempSkills);
        }
    }

    private void initFlowLayout(List<UserData.SkillsBean> tempSkills){
        flowLayout.removeAllViews();
        for(UserData.SkillsBean skillsBean : tempSkills) {
            TextView textView = new TextView(this);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.min_font));
            textView.setGravity(Gravity.CENTER);
            textView.setText(skillsBean.getSkillName());
            textView.setTextColor(getResources().getColor(R.color.font_gray_deep));
            textView.setBackground(getResources().getDrawable(R.drawable.btn_rbg_gray));
            textView.setPadding((int)(getResources().getDimension(R.dimen.space_middle)+0.5),
                    (int)(getResources().getDimension(R.dimen.space_min)+0.5),
                    (int)(getResources().getDimension(R.dimen.space_middle)+0.5),
                    (int)(getResources().getDimension(R.dimen.space_min)+0.5));
            flowLayout.addView(textView);
        }
    }

    private void initAboutTradeRv() {
        if(userData!=null) {

           tempIndustrys= userData.getIndustry();
            industrys= userData.getIndustry();
            mAboutTradeRv.setHasFixedSize(true);
            mAboutTradeRv.setLayoutManager(new GridLayoutManager(this, 3));
            indusAdapter= new MyIndustryAdapter(this, tempIndustrys);
            indusAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
                @Override
                public void itemSelect(int position) {

                }
            });
            mAboutTradeRv.setAdapter(indusAdapter);
        }
    }


    /**
     * 上传头像
     */
    private void uploadHeadImage() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_popupwindow, null);
        TextView btnCarema = (TextView) view.findViewById(R.id.btn_camera);
        TextView btnPhoto = (TextView) view.findViewById(R.id.btn_photo);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
        if(popupWindow==null){
            popupWindow= new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
            popupWindow.setOutsideTouchable(true);
        }
        View parent = LayoutInflater.from(this).inflate(getResourceId(), null);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });

        btnCarema.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到调用系统相机
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                startActivityForResult(intent, REQUEST_CAPTURE);
                popupWindow.dismiss();
            }
        });
        btnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到调用系统图库
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent,REQUEST_PICK);
                popupWindow.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 创建调用系统照相机待存储的临时文件
     *
     * @param savedInstanceState
     */
    private void createCameraTempFile(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.containsKey("tempFile")) {
            tempFile = (File) savedInstanceState.getSerializable("tempFile");
        } else {
            tempFile = new File(checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"),
                    System.currentTimeMillis() + ".jpg");
        }
    }

    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if(intent == null)
            return;
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == RESULT_OK) {
                    Uri uri = Uri.fromFile(tempFile);
//                    gotoClipActivity(Uri.fromFile(tempFile));
                    setImage(uri);//设置图片
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                if (resultCode == RESULT_OK) {
                    Uri uri = intent.getData();
                    setImage(uri);//设置图片
                }
                break;
            case REQUEST_CROP_PHOTO:  //剪切图片返回
                if (resultCode == RESULT_OK) {
                    final Uri uri = intent.getData();
                    if (uri == null) {
                        return;
                    }
                    String cropImagePath = getRealFilePathFromUri(getApplicationContext(), uri);
                    Bitmap bitMap = BitmapFactory.decodeFile(cropImagePath);
                    if (type == 1) {
                        ImageLoadUtil.loadCircle(mContext,bitMap,mHeaderIv);
                    }
                    //此处后面可以将bitMap转为二进制上传后台网络
                    //......

                }
                break;
            case  EditUserDataActivity.RESULT_CODE:
                if( resultCode != RESULT_OK)
                return;
                int id = intent.getIntExtra("id",0);
                if(id != 0){
                    String text = intent.getStringExtra(EditUserDataActivity.EDITEXT_FLAG);
                    ((TextView) findViewById(id)).setText(text);
                    setUserData(id,text);
                }
                break;

            case  MoreRoleActivity.ROLE_RESULT_CODE://技能
                try {
                    tempSkills = (List<UserData.SkillsBean>) intent.getSerializableExtra("role");
                    addSkill =new ArrayList<>();
                    delSkill = new ArrayList<>();
                    //获取添加集合
                    for (UserData.SkillsBean skill:tempSkills) {
                        if(!roles.contains(skill))
                            addSkill.add(skill);
                    }

                    //获取删除集合
                    for (UserData.SkillsBean skill:roles) {
                        if(!tempSkills.contains(skill))
                            delSkill.add(skill);
                    }
                    roleAdapter.updateAdapter(tempSkills);

                    initFlowLayout(tempSkills);

                }catch (Exception e){
                    roleAdapter.updateAdapter(null);
                    flowLayout.removeAllViews();
                }
                break;
            case  MoreRoleActivity.INDUSTRY_RESULT_CODE://行业
                try {
                    tempIndustrys =(List<UserData.IndustryBean>) intent.getSerializableExtra("industry");
                addIndustry = new ArrayList<>();
                delIndustry = new ArrayList<>();

                    for (UserData.IndustryBean industry:tempIndustrys){
                        if(!industrys.contains(industry)){
                            addIndustry.add(industry);
                        }

                    }
                    for (UserData.IndustryBean industry:industrys){
                        if(!tempIndustrys.contains(industry)){
                            delIndustry.add(industry);
                        }
                    }
                    indusAdapter.updateAdapter(tempIndustrys);
                }catch (Exception e){
                    indusAdapter.updateAdapter(null);
                }
                break;
            default: break;
        }
    }

    /**
     * 设置值
     * @param id
     * @param text
     */
    private void setUserData(int id, String text) {
        switch (id){
            case  R.id.file_tv_pet_name://昵称
                userData.setNickname(text);
                break;
            case  R.id.file_tv_user_name://姓名
                userData.setUsername(text);
                break;
            case  R.id.file_tv_sex://性别
                userData.setGender(text);
                break;
            case  R.id.file_tv_class://部门
                userData.setDepartment(text);
                break;
            case  R.id.file_tv_position://职位
                userData.setPosition(text);
                break;
            case  R.id.file_tv_phone://手机
                userData.setPhone(text);
                break;
            case  R.id.file_tv_introduce://一句话介绍
                userData.setUserIntro(text);
                break;
            default:
                break;
        }
    }

    /**
     * 设置图片
     * @param uri
     */
    private void setImage(final  Uri uri) {

        Observable.create(new Observable.OnSubscribe<Bitmap>() {
            @Override
            public void call(Subscriber<? super Bitmap> subscriber) {
                try {
                    Bitmap bitmap = ImageUtil.getBitmapFormUri(MyFileActivity.this,uri);
                    if(bitmap!=null){
                        tempImgPath+=System.currentTimeMillis()+"_upload.png";//保存临时文件的路径

                        boolean saveSuccess = ImageUtil.saveBitmap(bitmap,tempImgPath);
                        //保存成功则上传文件到服务器
                        if(saveSuccess){
                           uploadImage();
                            subscriber.onNext(bitmap);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Bitmap>(){
                    @Override
                    public void onCompleted() {

                    }
                    @Override
                    public void onError(Throwable e) {

                    }
                    @Override
                    public void onNext(Bitmap bitmap) {
                        ImageLoadUtil.loadCircle(mContext,tempImgPath,mHeaderIv);
                    }
                });
    }

    /**
     * 保存用户信息
     */
    private void saveUserData(){
        if(userData!=null){
            List<UserData.IndustryBean> industrys =  userData.getIndustry();
            String imgUrl = userData.getPortrait();

            boolean flag =false;
            if(imgUrl!=null&&imgUrl.contains("http")){
                flag =true;
            }

            JsonObject param = JsonUtil.getInstance().entityToJson(userData);
            if(param!=null){
                JsonArray rolesTemp = getRoles(addSkill);
                JsonArray delTemp = getRoles(delSkill);

                JsonArray industryTemp = getIndustry(addIndustry);
                JsonArray delIndustryTemp = getIndustry(delIndustry);
                if(flag){
                    param.remove("portrait");
                }
                param.remove("skills");
                param.remove("industry");
                if(industryTemp!=null)
                    param.add("addIndustryIds",industryTemp);

                if(delIndustryTemp!=null)
                    param.add("delIndustryIds",delIndustryTemp);

                if(rolesTemp!=null)
                param.add("addSkillIds",rolesTemp);
                if(delTemp!=null)
                    param.add("delSkillIds",delTemp);
                HttpHelper.getInstance(mContext).updateUserInfo(param,UPDATE_USER_INFO,this);
            }else{
                ToasUtil.toast(mContext,"解析userData出错!");
            }

        }

    }

    private JsonArray getRoles(List<UserData.SkillsBean> roles) {
        JsonArray  array = new JsonArray();
        if(roles!=null)
        for (UserData.SkillsBean role:roles) {
            if(role!=null)
                array.add(role.getSkillId());
        }
        if(array.size()>0)
        return array;
        else return null;
    }
    private JsonArray getIndustry(List<UserData.IndustryBean> industrys) {
        JsonArray  array = new JsonArray();
        if(industrys!=null)
        for (UserData.IndustryBean industry:industrys) {
            if(industry!=null){
                array.add(industry.getIndustryId());
            }
        }
        if(array.size()>0)
        return  array;
        return null;
    }

    /**
     * 上传图片到服务器
     */
    private void uploadImage() {
        String key = String.format("user/info/icon/%d/%d", userData.getUuid(), UploadLogic.getTime());
        UploadLogic  upload = new UploadLogic(mContext,tempImgPath,key);
        upload.setCallBack(new UploadLogic.UploadCallBack() {
            @Override
            public void done(boolean success) {
                if(success){
                    ToasUtil.toast(mContext,"上传头像成功!");
                }else {
                    ToasUtil.toast(mContext,"上传头像失败!");
                }
            }
            @Override
            public void uploadSuccess(String url) {
                userData.setPortrait(url);
            }
        });
        upload.uploadImage();
    }

    /**
     * 打开截图界面
     *
     * @param uri
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.putExtra("type", type);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }


    @Override
    public void onStart(int requestType) {
        loading.show();
    }

    @Override
    public void onCompleted(int requestType) {
        loading.cancel();
    }

    @Override
    public void onError(int requestType) {
        loading.cancel();
        if(requestType == WEICHAT_DATA_COMMIT_CODE)
            ToasUtil.toast(this, "抱歉，微信信息提交失败，请稍后重试");
    }

    @Override
    public void onNext(IModel data, int requestType) {
        if(requestType == WEICHAT_DATA_COMMIT_CODE){
            if(data.getErrcode() == 0 && weiChatBindModel != null){
                bindWeiChatLly.setVisibility(View.GONE);
                if(weiChatBindModel.getSex() == 1) {
                    mSexTv.setText("男");
                    setUserData(R.id.file_tv_sex, "男");
                } else if(weiChatBindModel.getSex() == 2){
                    mSexTv.setText("女");
                    setUserData(R.id.file_tv_sex, "女");
                }
                userData.setNickname(weiChatBindModel.getNickname());
                userData.setPortrait(weiChatBindModel.getHeadimgurl());
                mPetNameTv.setText(userData.getNickname());
                ImageLoadUtil.loadCircle(mContext,userData.getPortrait(),mHeaderIv);
            } else{
                onError(requestType);
            }
            return;
        }
        if(data.getErrcode()==0){
            ToasUtil.toast(mContext,"保存成功!");
            roles = userData.getSkills();
            industrys = userData.getIndustry();
           personLogic.getUserData();
            finish();
        }else{
            ToasUtil.toast(mContext,"保存失败!");
        }
    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(broadcaseReciver);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            saveDialog.show();
        return true;
    }


    /* 微信认证时 http get请求回调 */
    @Override
    public void onError(int requestCode, Throwable e) {
        loading.cancel();
        if(requestCode == WEICHAT_GET_USER_DATA){
            ToasUtil.toast(this, "抱歉，获取 access_token 失败，请稍后重试");
        } else if(requestCode == WEICHAT_GET_USER_DATA){
            ToasUtil.toast(this, "抱歉，获取微信个人信息失败，请稍后从重试");
        }
    }
    @Override
    public void onNext(int requestCode, String data) {
        if(requestCode == WEICHAT_ACCESS_TOKEN_CODE){
            try {
                JSONObject json = new JSONObject(data);
                String accessToken = json.getString("access_token");
                String openId = json.getString("openid");
                String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                        + accessToken + "&openid=" + openId;
                HttpGet.httpGetData(WEICHAT_GET_USER_DATA, url, this);
            } catch (JSONException e) {
                onError(requestCode, e);
            }
        } else if(requestCode == WEICHAT_GET_USER_DATA){
            weiChatBindModel = JsonUtil.getInstance().jsonToObject(data, WeiChatBindModel.class);

            JsonObject param = new JsonObject();
            param.addProperty("token", HttpHelper.token);
            param.addProperty("nickname", weiChatBindModel.getNickname());
            param.addProperty("gender", weiChatBindModel.getSex());
            param.addProperty("portrait", weiChatBindModel.getHeadimgurl());
            param.addProperty("province", weiChatBindModel.getProvince());
            param.addProperty("city", weiChatBindModel.getCity());
            param.addProperty("country", weiChatBindModel.getCountry());
            param.addProperty("openid", weiChatBindModel.getOpenid());
            param.addProperty("unionid", weiChatBindModel.getUnionid());
            HttpHelper.getInstance(this).bindWeiChat(param, WEICHAT_DATA_COMMIT_CODE, this);
        }
    }

    private class WeiChatBindModel{

        /**
         * openid : oec3bwObZ2_RTiw4tgJt9mUcmHTQ
         * nickname : 方块8
         * sex : 1
         * language : zh_CN
         * city : Shantou
         * province : Guangdong
         * country : CN
         * headimgurl : http://wx.qlogo.cn/mmopen/O5IB5rptd1qDhHhsjso7c22Via7cjJW84d9XEWLDWPOQzS0wJuWicvU09Ikfdq7IicTO2iayvnYuffrviaAtUibuwXXlVOAyFTBQe9/0
         * privilege : []
         * unionid : ojW7kwGAcHW990H_QerXRUfFJ-jI
         */

        private String openid;
        private String nickname;
        private int sex;
        private String language;
        private String city;
        private String province;
        private String country;
        private String headimgurl;
        private String unionid;
        private List<String> privilege;

        public String getOpenid() {
            return openid;
        }

        public void setOpenid(String openid) {
            this.openid = openid;
        }

        public String getNickname() {
            return nickname;
        }

        public void setNickname(String nickname) {
            this.nickname = nickname;
        }

        public int getSex() {
            return sex;
        }

        public void setSex(int sex) {
            this.sex = sex;
        }

        public String getLanguage() {
            return language;
        }

        public void setLanguage(String language) {
            this.language = language;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getProvince() {
            return province;
        }

        public void setProvince(String province) {
            this.province = province;
        }

        public String getCountry() {
            return country;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public String getHeadimgurl() {
            return headimgurl;
        }

        public void setHeadimgurl(String headimgurl) {
            this.headimgurl = headimgurl;
        }

        public String getUnionid() {
            return unionid;
        }

        public void setUnionid(String unionid) {
            this.unionid = unionid;
        }

        public List<String> getPrivilege() {
            return privilege;
        }

        public void setPrivilege(List<String> privilege) {
            this.privilege = privilege;
        }
    }
}
